<template>
  <view class="book-container">
    <view class="teacher-card">
      <view class="teacher-info">
        <u-avatar :src="teacherInfo.avatar" size="60"></u-avatar>
        <view class="info-content">
          <text class="teacher-name">{{ teacherInfo.name }}</text>
          <text class="teacher-school">{{ teacherInfo.school }}</text>
        </view>
        <view class="hourly-rate">
          <text class="price">¥{{ teacherInfo.hourlyRate }}</text>
          <text class="unit">/时</text>
        </view>
      </view>
    </view>
    
    <view class="form-section">
      <u-form :model="formData" ref="formRef" label-width="180">
        <u-form-item label="科目" required>
          <u-input 
            v-model="formData.subject" 
            placeholder="请输入科目（如：数学）"
            :border="true"
          ></u-input>
        </u-form-item>
        
        <u-form-item label="年级">
          <u-input 
            v-model="formData.grade" 
            placeholder="请输入年级（如：高一）"
            :border="true"
          ></u-input>
        </u-form-item>
        
        <u-form-item label="授课方式" required>
          <u-radio-group v-model="formData.teachingType" placement="column">
            <u-radio name="OFFLINE">线下授课</u-radio>
            <u-radio name="ONLINE">线上授课</u-radio>
            <u-radio name="BOTH">都可以</u-radio>
          </u-radio-group>
        </u-form-item>
        
        <u-form-item label="总课时" required>
          <u-input 
            v-model.number="formData.totalHours" 
            type="number"
            placeholder="请输入总课时数"
            :border="true"
          ></u-input>
        </u-form-item>
        
        <u-form-item label="开始日期" required>
          <picker mode="date" :value="formData.startDate" @change="onStartDateChange">
            <view class="date-picker">
              <text :class="{ placeholder: !formData.startDate }">
                {{ formData.startDate || '请选择开始日期' }}
              </text>
              <u-icon name="arrow-right" size="16" color="#ccc"></u-icon>
            </view>
          </picker>
        </u-form-item>
        
        <u-form-item label="结束日期">
          <picker mode="date" :value="formData.endDate" @change="onEndDateChange">
            <view class="date-picker">
              <text :class="{ placeholder: !formData.endDate }">
                {{ formData.endDate || '请选择结束日期' }}
              </text>
              <u-icon name="arrow-right" size="16" color="#ccc"></u-icon>
            </view>
          </picker>
        </u-form-item>
        
        <u-form-item label="上课地址" :required="formData.teachingType === 'OFFLINE'">
          <u-input 
            v-model="formData.address" 
            type="textarea"
            placeholder="请输入详细地址"
            :border="true"
            :rows="3"
          ></u-input>
        </u-form-item>
        
        <u-form-item label="学生姓名">
          <u-input 
            v-model="formData.studentName" 
            placeholder="请输入学生姓名"
            :border="true"
          ></u-input>
        </u-form-item>
        
        <u-form-item label="联系电话">
          <u-input 
            v-model="formData.contactPhone" 
            placeholder="请输入联系电话"
            :border="true"
          ></u-input>
        </u-form-item>
        
        <u-form-item label="特殊要求">
          <u-input 
            v-model="formData.requirements" 
            type="textarea"
            placeholder="请输入特殊要求（选填）"
            :border="true"
            :rows="4"
          ></u-input>
        </u-form-item>
      </u-form>
    </view>
    
    <!-- 费用明细 -->
    <view class="cost-section card">
      <view class="section-title">费用明细</view>
      <view class="cost-item">
        <text class="label">时薪</text>
        <text class="value">¥{{ teacherInfo.hourlyRate }}/时</text>
      </view>
      <view class="cost-item">
        <text class="label">总课时</text>
        <text class="value">{{ formData.totalHours || 0 }}小时</text>
      </view>
      <view class="cost-divider"></view>
      <view class="cost-item total">
        <text class="label">合计</text>
        <text class="value">¥{{ totalAmount }}</text>
      </view>
    </view>
    
    <!-- 底部提交按钮 -->
    <view class="bottom-actions">
      <view class="total-price">
        <text class="label">总计：</text>
        <text class="amount">¥{{ totalAmount }}</text>
      </view>
      <u-button 
        type="primary"
        :loading="submitting"
        @click="handleSubmit"
        :custom-style="{
          borderRadius: '50rpx',
          height: '80rpx',
          flex: 1,
          backgroundColor: '#3cc51f',
          borderColor: '#3cc51f',
          marginLeft: '20rpx'
        }"
      >
        提交预约
      </u-button>
    </view>
    
  </view>
</template>

<script>
import { getTeacherDetail } from '@/api/teacher'
import { createOrder } from '@/api/order'

export default {
  data() {
    return {
      teacherId: null,
      teacherInfo: {
        id: null,
        name: '',
        avatar: '',
        school: '',
        hourlyRate: 0
      },
      formData: {
        teacherId: null,
        subject: '',
        grade: '',
        teachingType: 'OFFLINE',
        totalHours: 10,
        startDate: '',
        endDate: '',
        address: '',
        studentName: '',
        contactPhone: '',
        requirements: ''
      },
      submitting: false
    }
  },
  
  computed: {
    totalAmount() {
      return (this.teacherInfo.hourlyRate * (this.formData.totalHours || 0)).toFixed(2)
    }
  },
  
  onLoad(options) {
    if (options.teacherId) {
      this.teacherId = options.teacherId
      this.formData.teacherId = options.teacherId
      this.loadTeacherInfo()
    }
  },
  
  methods: {
    async loadTeacherInfo() {
      try {
        const response = await getTeacherDetail(this.teacherId)
        
        if (response.code === 200 && response.data) {
          const data = response.data
          this.teacherInfo = {
            id: data.id,
            name: data.realName || '教员',
            avatar: data.avatarUrl || '/static/icons/default-avatar.png',
            school: data.school || '',
            hourlyRate: parseFloat(data.hourlyRate) || 0
          }
        }
      } catch (error) {
        console.error('加载教员信息失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    },
    
    // 开始日期选择
    onStartDateChange(e) {
      console.log('选择开始日期:', e.detail.value)
      this.formData.startDate = e.detail.value
    },
    
    // 结束日期选择
    onEndDateChange(e) {
      console.log('选择结束日期:', e.detail.value)
      this.formData.endDate = e.detail.value
    },
    
    validateForm() {
      if (!this.formData.subject) {
        uni.showToast({ title: '请输入科目', icon: 'none' })
        return false
      }
      
      if (!this.formData.teachingType) {
        uni.showToast({ title: '请选择授课方式', icon: 'none' })
        return false
      }
      
      if (!this.formData.totalHours || this.formData.totalHours <= 0) {
        uni.showToast({ title: '请输入有效的课时数', icon: 'none' })
        return false
      }
      
      if (!this.formData.startDate) {
        uni.showToast({ title: '请选择开始日期', icon: 'none' })
        return false
      }
      
      if (this.formData.teachingType === 'OFFLINE' && !this.formData.address) {
        uni.showToast({ title: '线下授课请填写上课地址', icon: 'none' })
        return false
      }
      
      return true
    },
    
    async handleSubmit() {
      if (!this.validateForm()) {
        return
      }
      
      // 打印提交数据，用于调试
      console.log('提交的数据:', this.formData)
      
      this.submitting = true
      
      try {
        const response = await createOrder(this.formData)
        
        if (response.code === 200) {
          uni.showModal({
            title: '预约成功',
            content: '您的预约已提交，请尽快完成支付',
            showCancel: false,
            success: () => {
              // 跳转到订单详情或订单列表
              uni.redirectTo({
                url: `/pages/order/detail?id=${response.data.id}`
              })
            }
          })
        }
      } catch (error) {
        console.error('提交预约失败:', error)
        uni.showToast({
          title: error.message || '预约失败',
          icon: 'none',
          duration: 3000
        })
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.book-container {
  min-height: 100vh;
  background: #f8f9fa;
  padding-bottom: 120rpx;
}

.teacher-card {
  background: white;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .teacher-info {
    display: flex;
    align-items: center;
    
    .info-content {
      flex: 1;
      margin-left: 20rpx;
      
      .teacher-name {
        display: block;
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .teacher-school {
        font-size: 26rpx;
        color: #666;
      }
    }
    
    .hourly-rate {
      text-align: right;
      
      .price {
        font-size: 36rpx;
        font-weight: bold;
        color: #3cc51f;
      }
      
      .unit {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
}

.form-section {
  background: white;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.date-picker {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
  
  text {
    font-size: 28rpx;
    color: #333;
    
    &.placeholder {
      color: #999;
    }
  }
}

.cost-section {
  background: white;
  padding: 30rpx;
  margin: 20rpx 30rpx;
  border-radius: 16rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .cost-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16rpx 0;
    
    .label {
      font-size: 28rpx;
      color: #666;
    }
    
    .value {
      font-size: 28rpx;
      color: #333;
    }
    
    &.total {
      .label {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .value {
        font-size: 36rpx;
        font-weight: bold;
        color: #3cc51f;
      }
    }
  }
  
  .cost-divider {
    height: 1rpx;
    background: #f0f0f0;
    margin: 16rpx 0;
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 24rpx 30rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.08);
  
  .total-price {
    .label {
      font-size: 26rpx;
      color: #666;
    }
    
    .amount {
      font-size: 36rpx;
      font-weight: bold;
      color: #3cc51f;
      margin-left: 8rpx;
    }
  }
}
</style>

